﻿#region references
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using AjaxControlToolkit;

/* Project dependencies */
using IcaGames.Objects;
using IcaGames.Database.ObjectManagement;
using IcaGames.Security;
using IcaGames.Logging;
#endregion

public partial class IcaGamesMaster : System.Web.UI.MasterPage
{
    #region public attributes
    public decimal[] _cartPrice
    {
        set { Session["cartPrice"] = value; }
        get
        {
            decimal[] ret = null;
            if (Session["cartPrice"] != null)
                ret = (decimal[])Session["cartPrice"];
            return ret;
        }
    }
    #endregion

    protected override void OnInit(EventArgs e)
    {
        InitializeCustomControl();
        base.OnInit(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.User.Identity.IsAuthenticated) { RefreshShoppingCart(); }
        if (!IsPostBack)
        {
            BindDropDown();
            Page.MaintainScrollPositionOnPostBack = true;
            txtSearch.Attributes["onclick"] = "ClearTextBox(this.id)";
        }
    }

    /*
     * Function that constantly refreshes the shopping cart of the authenticated user.
     */ 
    private void RefreshShoppingCart()
    {
        LinkButton lbCartInfo = ((LinkButton)LoginView1.FindControl("lbCartInfo"));
        lbCartInfo.Text = _cartPrice[1] + " artikel(en) totaalprijs: € " + String.Format("{0:0,##}",
            _cartPrice[0].ToString().Replace('.', ','));
    }

    /*
     * Function that binds the DropDownList that is on the advanced search page.
     */ 
    private void BindDropDown()
    {
        ddlPlatform.DataSource = null;
        List<Platform> platforms = new List<Platform>();
        List<string> items = new List<string>();

        if (PlatformManagement.GetPlatforms(platforms))
        {
            foreach (Platform p in platforms)
            {
                string descr = PlatformDescription.GetDescription(p);
                items.Add(descr);
            }
            ddlPlatform.DataSource = items;
            ddlPlatform.DataBind();
        }
    }

    /*
     * Function that is used to initialize the Click event for the Register form.
     */ 
    private void InitializeCustomControl()
    {
        this.CreateUser.Click += new EventHandler(this.RegisterUser);
        this.Load += new EventHandler(this.Page_Load);
    }

    /*
     * Function that handles the registration of a new user.
     */ 
    private void RegisterUser(object sender, EventArgs e)
    {
        try
        {
            CustomMembershipProvider provider = Membership.Provider as CustomMembershipProvider;
            /* Create a new user and store the information in the database */
            MembershipUser user = provider.CreateUser(CreateUser.TextBoxEmail, CreateUser.TextBoxPassword,
                CreateUser.TextBoxFirstName, CreateUser.TextBoxLastName, CreateUser.TextBoxPrefix);

            if (user == null)
            {
                /* Prevent the ModalPopupExtender to disappear on postback when an error occures */
                ModalPopupExtender mPopupRegister = LoginView1.FindControl("Login1").FindControl("mPopupRegister") as ModalPopupExtender;
                mPopupRegister.Show();
                lblError.Text = "Er is een fout opgetreden tijdens de registratie. Probeer het nogmaals.";
            }
            else
            {
                /* Clear the register form textboxes */
                CreateUser.ClearFields();
            }
        }
        catch (Exception ex)
        {
            Log.CreateLog("Exception while registering new user", "ICAGAMESMASTER");
            Log.CreateLog(ex.Message, "ICAGAMESMASTER");
        }
    }

    /*
     * Function to quickly search for a game.
     */
    protected void SearchGame(object sender, EventArgs e)
    {
        Session["viewIndex"] = null;
        string searchQuery = txtSearch.Text.Replace(' ', '_');
        Response.Redirect("~/Search.aspx?q=" + searchQuery);
    }

    /*
     * Function to use the advanced search for a game.
     */ 
    protected void SearchGameAdvanced(object sender, EventArgs e)
    {
        Session["viewIndex"] = null;
        
        if (rbGame.Checked) 
        {
            int index = ddlPlatform.SelectedIndex + 1;
            string queryString = txtSearchGameTitle.Text + 
                "&cat=games" +
                "&size=" + txtSearchGameSize.Text + 
                "&platform=" + index;
            Response.Redirect("~/AdvancedSearch.aspx?q=" + queryString);
        }
        else 
        { 
            Response.Redirect("~/AdvancedSearch.aspx?q=" + txtSearchGameTitle.Text +
                "&cat=publishers"); 
        }
    }

    /*
     * Function that checks which RadioButton is checked and, depending on that, displays a Panel with extra information.
     */ 
    protected void CheckRadioButtons(object sender, EventArgs e)
    {
        if (rbGame.Checked) { pnlGameSearch.Visible = true; mPopupAdvancedSearch.Show(); lblSearchGameTitle.Text = "Titel:"; }
        else { pnlGameSearch.Visible = false; mPopupAdvancedSearch.Show(); lblSearchGameTitle.Text = "Uitgever:"; }
    }

    /*
     * Function that checks if a authenticated user has a saved shopping cart.
     */ 
    protected void CheckUserShoppingCart(object sender, EventArgs e)
    {
        CustomMembershipProvider provider = Membership.Provider as CustomMembershipProvider;
        TextBox userName = ((Login)LoginView1.FindControl("Login1")).FindControl("UserName") as TextBox;
        int userId = provider.GetUserId(userName.Text);
        ShoppingCart cart = CartManagement.GetShoppingCart(userId, "Nee");
        cart.Games = CartManagement.GetShoppingCartGames(cart.CartId);
        _cartPrice = CartManagement.RefreshShoppingCart(cart.Games);
    }

    /*
     * Function that redirects the user to his/her shopping cart.
     */ 
    protected void ToShoppingCart(object sender, EventArgs e)
    {
        Response.Redirect("~/Cart.aspx");
    }

    /*
     * Function that redirects the user to the Games page.
     */ 
    protected void ToGamesPage(object sender, EventArgs e)
    {
        Response.Redirect("~/Games.aspx?c=all");
    }

    /*
     * Function that redirects the user to the Games page with Game results for the selected Platform.
     */ 
    protected void ToGamesPagePlatform(object sender, EventArgs e)
    {
        LinkButton lbToGames = sender as LinkButton;
        Response.Redirect("~/Games.aspx?c=" + lbToGames.CommandArgument);
    }
}
